package com.cn.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *     *      1.乱码
 *      *      2.接收前端数据
 *      *      3.封装对象
 *      *      4.调用服务逻辑层
 *      *      5.得到返回值对象 resultModel
 *      *      6.将数据返回给前端  json
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        解决乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
// 接收前端传递过来的数据
        //username对应的时前端json对象的key值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//封装model
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
//    调用服务逻辑层
        UserService userService = new UserServiceImpl();
//        必须要有一个返回值，返回值类型应该是什么？
//        返回给前端对象的统一属性或者接口
        ResultModel resultModel = userService.login(userModel);
//    将返回值返回给前端
        resp.getWriter().print(JSONObject.toJSON(resultModel));//默认返回给前端是字符串，
    }

    public static void main(String[] args) {
        String username = "username";
        String password = "password";
//封装model
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);

        System.out.println(JSONObject.toJSON(userModel));
    }
}
